import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout


class ExchangeRateApp(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        # 创建美元标签和输入框
        self.usd_label = QLabel('美元')
        self.usd_input = QLineEdit()

        # 创建转换按钮
        self.convert_button = QPushButton('转换')
        self.convert_button.clicked.connect(self.convert_currency)

        # 创建人民币标签和输出框
        self.cny_label = QLabel('人民币')
        self.cny_output = QLineEdit()
        self.cny_output.setReadOnly(True)

        # 创建清空按钮
        self.clear_button = QPushButton('清空')
        self.clear_button.clicked.connect(self.clear_fields)

        # 布局设置
        layout = QVBoxLayout()
        layout.addWidget(self.usd_label)
        layout.addWidget(self.usd_input)
        layout.addWidget(self.convert_button)
        layout.addWidget(self.cny_label)
        layout.addWidget(self.cny_output)
        layout.addWidget(self.clear_button)

        self.setLayout(layout)

        self.setWindowTitle('汇率转换程序')
        self.show()

    def convert_currency(self):
        try:
            usd_amount = float(self.usd_input.text())
            # 这里假设汇率为7，实际应用中应获取实时汇率
            exchange_rate = 7
            cny_amount = usd_amount * exchange_rate
            self.cny_output.setText(str(cny_amount))
        except ValueError:
            self.cny_output.setText('请输入有效的数字')

    def clear_fields(self):
        self.usd_input.clear()
        self.cny_output.clear()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ExchangeRateApp()
    sys.exit(app.exec_())
